package com.gzz.orchid.common.webmvc.securityjwt;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author higmd
 */
@Slf4j
public class JwtRequestFilter extends OncePerRequestFilter {

    //    private final UserDetailsService userDetailsService;
    //
    //    public JwtRequestFilter(UserDetailsService userDetailsService) {
    //        this.userDetailsService = userDetailsService;
    //    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // 获取当前请求的uri
        String uri = request.getRequestURI();
        log.info("拦截-请求路径:" + uri);
        // 获取请求头中的token
        String authToken = JwtUtil.extractToken(request);
        if (!StringUtils.isBlank(authToken)) {
            try {
                DecodedJWT decodedJwt = JwtUtil.parseJWT(authToken);
                System.out.println(decodedJwt.getHeader());
                System.out.println(decodedJwt.getPayload());
                System.out.println(decodedJwt.getSignature());
                System.out.println(decodedJwt.getIssuer());
                System.out.println(decodedJwt.getAudience());
                System.out.println(decodedJwt.getExpiresAt());
                System.out.println(decodedJwt.getNotBefore());
                System.out.println(decodedJwt.getIssuedAt());
                System.out.println(decodedJwt.getSubject());
                System.out.println(decodedJwt.getId());
                System.out.println(decodedJwt.getAlgorithm());
                System.out.println(decodedJwt.getType());
                System.out.println(decodedJwt.getKeyId());
                System.out.println(decodedJwt.getClaims());
                JwtAuthToken jwtToken = new JwtAuthToken();

                //标记为已认证
                jwtToken.setAuthenticated(true);
                //将登录信息写入认证上下文
                SecurityContextHolder
                        .getContext()
                        .setAuthentication(jwtToken);
            } catch (JWTVerificationException e) {
                log.warn("jwt token 非法");
                //清空 上下文
                SecurityContextHolder.clearContext();
                // 响应客户端
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

}